package com.example.spsaveqqty.guides;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.spsaveqqty.R;
import com.example.spsaveqqty.PersonalCenterActivity;
import com.example.spsaveqqty.attraction.AtractionsActivity;
import com.example.spsaveqqty.attraction.Attraction;
import com.example.spsaveqqty.attraction.AttractionDao;
import com.example.spsaveqqty.map_weather;
import com.example.spsaveqqty.userManage.User;

import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class GuidesMainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton refreshBtn1,publishBtn,ib_search,ib_user,ib_map,ib_place;
    private EditText et_search;
    private ListView lv1;//listview实现分栏显示
    private ArrayList<Guide> guides;
    private GuideDao guideDao;
    private String name;
    private TextView tv_noGuides;
    //联想搜索列表所在布局
    ConstraintLayout searchList;
    //第一次点击事件发生的时间
    private long mExitTime;

    // 是否退出程序
    private static Boolean isExit = false;
    // 定时触发器
    private static Timer tExit = null;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guides_main);
        requestWritePermission();
        //设置界面打开时不弹出输入键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        ib_user = findViewById(R.id.ib_user);//用户头像按钮，以便进入个人中心
        ib_user.setOnClickListener(this);
        refreshBtn1 = findViewById(R.id.ib_refresh);//刷新按钮
        refreshBtn1.setOnClickListener(this);
        publishBtn = findViewById(R.id.ib_publish);//发布按钮
        publishBtn.setOnClickListener(this);
        ib_search = findViewById(R.id.ib_search);//搜索按钮
        ib_search.setOnClickListener(this);
        et_search = findViewById(R.id.et_search);//搜索输入框
        ib_map = findViewById(R.id.imageButton1);//导航栏的地图主页按钮
        ib_map.setOnClickListener(this);
        ib_place = findViewById(R.id.imageButton3);//导航栏的景区主页按钮
        ib_place.setOnClickListener(this);
        //设置头像格式
        if (!TextUtils.isEmpty(User.FLAG)){
            if (User.FLAG.equals("1")){		//	相册
                Bitmap bitmap = BitmapFactory.decodeFile(User.USERPICTURE);
                bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                ib_user.setImageBitmap(bitmap);
            }else if (User.FLAG.equals("2")){	//	拍照
                Uri imgUri = Uri.parse(User.USERPICTURE);
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                    bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                    bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                    ib_user.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        String str = null;
        str = (String) getIntent().getSerializableExtra("search");
        et_search.setText(str);
        if (str == null) {
            name = "all";
        }
        else {
            name = str;//没有搜索则显示全部
        }
        if(et_search.getFreezesText())
            guideDao = new GuideDao(GuidesMainActivity.this);
        guides = new ArrayList<Guide>();
        guides = guideDao.getGuides(name);
        if(guides.size() == 0)
        {
            tv_noGuides = findViewById(R.id.tv_noGuides);
            tv_noGuides.setText("暂时没有该景区的旅游攻略哦");
        }
        lv1 = findViewById(R.id.list_item1);
        //添加数据适配器
        MyAdpter my1 = new MyAdpter();
        lv1.setAdapter(my1);
    }
    //设置图片格式
    public Bitmap toRoundBitmap(Bitmap bitmap){
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int r=0;
        //取最短边做边长
        if(width<height){
            r=width;
        }else{
            r=height;
        }
        //构建一个bitmap
        Bitmap backgroundBm=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        //new一个Canvas，在backgroundBmp上画图
        Canvas canvas=new Canvas(backgroundBm);
        Paint p=new Paint();
        //设置边缘光滑，去掉锯齿
        p.setAntiAlias(true);
        RectF rect=new RectF(0, 0, r, r);
        //通过制定的rect画一个圆角矩形，当圆角X轴方向的半径等于Y轴方向的半径时，
        //且都等于r/2时，画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r/2, r/2, p);
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }
    //导航栏点击事件处理
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_refresh://刷新页面
            {
                Intent intent = new Intent(GuidesMainActivity.this, GuidesMainActivity.class);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
            break;
            case R.id.ib_publish://发布页面
            {
                et_search.setText(null);
                Intent intent = new Intent(GuidesMainActivity.this, PublishActivity.class);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
            break;
            case R.id.ib_user://头像按钮
            {
                et_search.setText(null);
                Intent intent = new Intent(GuidesMainActivity.this, PersonalCenterActivity.class);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
            break;
            case R.id.imageButton1://地图按钮
            {
                Intent intent = new Intent(GuidesMainActivity.this, map_weather.class);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
            break;
            case R.id.imageButton3://景区按钮
            {
                AttractionDao dao = new AttractionDao(GuidesMainActivity.this);
                List<Attraction> rankList = null;
                rankList = dao.selectByOrder();

                Intent intent = new Intent(GuidesMainActivity.this, AtractionsActivity.class);
                intent.putExtra("rkList", (Serializable) rankList);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
            break;
            case R.id.ib_search://搜索
            {
                Intent intent = new Intent();
                intent.putExtra("search", et_search.getText().toString());
                intent.setClass(GuidesMainActivity.this, GuidesMainActivity.class);
                startActivity(intent);
                GuidesMainActivity.this.finish();//关闭当前页面
            }
        }
    }

    //自定义数据适配器
    class MyAdpter extends BaseAdapter{

        @Override
        public int getCount() {
            if (guides.size() % 2 > 0) {
                return guides.size() / 2 + 1;
            } else {
                return guides.size() / 2;
            }
        }

        @Override
        public Object getItem(int position) {
            return guides.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyHolder mh;
            if(convertView == null){
                mh = new MyHolder();
                //将布局文件转换成view对象
                convertView = View.inflate(GuidesMainActivity.this, R.layout.list_item,
                        null);
                //找到界面中的控件
                mh.iv_headImage = convertView.findViewById(R.id.iv_headImage);
                mh.iv_picture = convertView.findViewById(R.id.iv_picture);
                mh.tv_title = convertView.findViewById(R.id.tv_title);
                mh.tv_location = convertView.findViewById(R.id.tv_location);
                mh.tv_date = convertView.findViewById(R.id.tv_date);
                mh.iv_headImage1 = convertView.findViewById(R.id.iv_headImage1);
                mh.iv_picture1 = convertView.findViewById(R.id.iv_picture1);
                mh.tv_title1 = convertView.findViewById(R.id.tv_title1);
                mh.tv_location1 = convertView.findViewById(R.id.tv_location1);
                mh.tv_date1 = convertView.findViewById(R.id.tv_date1);
                convertView.setTag(mh);
            }else{
                mh = (MyHolder)convertView.getTag();
            }
            int distance = guides.size() - position * 2;
            int cellCount = distance >= 2 ? 2 : distance;
            final List<Guide> itemList = guides.subList(position * 2, position * 2 + cellCount);
            String[] pic;
            Bitmap bitmap, bp;
            if (itemList.size() > 0) {
                pic = itemList.get(0).getPicture();
                //设置头像格式
                if(!TextUtils.isEmpty(itemList.get(0).getIconFlag())) {
                    if (itemList.get(0).getIconFlag().equals("1")) {        //	相册
                        Bitmap bitmap1 = BitmapFactory.decodeFile(itemList.get(0).getProducer_image());
                        bitmap1 = Bitmap.createScaledBitmap(bitmap1, 200, 200, true);
                        bitmap1 = toRoundBitmap(bitmap1);//调用自己写的方法把bitmap转成圆形
                        mh.iv_headImage.setImageBitmap(bitmap1);
                    } else if (itemList.get(0).getIconFlag().equals("2")) {    //	拍照
                        Uri imgUri = Uri.parse(itemList.get(0).getProducer_image());
                        try {
                            Bitmap bitmap1 = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                            bitmap1 = Bitmap.createScaledBitmap(bitmap1, 200, 200, true);
                            bitmap1 = toRoundBitmap(bitmap1);//调用自己写的方法把bitmap转成圆形
                            mh.iv_headImage.setImageBitmap(bitmap1);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //设置主图
                bp = BitmapFactory.decodeFile(pic[0]);
                bp = Bitmap.createScaledBitmap(bp, 200, 200, true);
                mh.iv_picture.setImageBitmap(bp);
                //主图点击事件，跳转到详情页面
                mh.iv_picture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", itemList.get(0).getTitle());
                        bundle.putString("conent", itemList.get(0).getConent());
                        bundle.putString("datetime", itemList.get(0).getDatetime());
                        bundle.putString("place_name", itemList.get(0).getPlace_name());
                        bundle.putString("image", itemList.get(0).getProducer_image());
                        bundle.putString("producer_name", itemList.get(0).getProducer_name());
                        bundle.putStringArray("pictures", itemList.get(0).getPicture());
                        bundle.putString("flag", itemList.get(0).getIconFlag());//获取头像flag
                        Intent intent = new Intent();
                        intent.putExtras(bundle);
                        intent.setClass(GuidesMainActivity.this, StraInfoActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        GuidesMainActivity.this.finish();
                    }
                });
                mh.tv_title.setText(itemList.get(0).getTitle());
                mh.tv_location.setText(itemList.get(0).getPlace_name());
                mh.tv_date.setText(itemList.get(0).getDatetime());
                //单数时，右栏不显示
                if(itemList.size() == 1){
                    mh.iv_headImage1.setVisibility(View.INVISIBLE);
                    mh.iv_picture1.setVisibility(View.INVISIBLE);
                    mh.tv_title1.setVisibility(View.INVISIBLE);
                    mh.tv_location1.setVisibility(View.INVISIBLE);
                    mh.tv_date1.setVisibility(View.INVISIBLE);
                }

                if (itemList.size() > 1) {
                    mh.iv_headImage1.setVisibility(View.VISIBLE);
                    mh.iv_picture1.setVisibility(View.VISIBLE);
                    mh.tv_title1.setVisibility(View.VISIBLE);
                    mh.tv_location1.setVisibility(View.VISIBLE);
                    mh.tv_date1.setVisibility(View.VISIBLE);
                    pic = itemList.get(1).getPicture();
                    //设置头像格式
                    if(!TextUtils.isEmpty(itemList.get(1).getIconFlag())) {
                        if (itemList.get(1).getIconFlag().equals("1")) {        //	相册
                            Bitmap bitmap2 = BitmapFactory.decodeFile(itemList.get(1).getProducer_image());
                            bitmap2 = Bitmap.createScaledBitmap(bitmap2, 200, 200, true);
                            bitmap2 = toRoundBitmap(bitmap2);//调用自己写的方法把bitmap转成圆形
                            mh.iv_headImage1.setImageBitmap(bitmap2);
                        } else if (itemList.get(1).getIconFlag().equals("2")) {    //	拍照
                            Uri imgUri = Uri.parse(itemList.get(1).getProducer_image());
                            try {
                                Bitmap bitmap2 = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                                bitmap2 = Bitmap.createScaledBitmap(bitmap2, 200, 200, true);
                                bitmap2 = toRoundBitmap(bitmap2);//调用自己写的方法把bitmap转成圆形
                                mh.iv_headImage1.setImageBitmap(bitmap2);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //设置主图
                    bp = BitmapFactory.decodeFile(pic[0]);
                    bp = Bitmap.createScaledBitmap(bp, 200, 200, true);
                    mh.iv_picture1.setImageBitmap(bp);
                    //主图点击事件，跳转到详情页面
                    mh.iv_picture1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("title", itemList.get(1).getTitle());
                            bundle.putString("conent", itemList.get(1).getConent());
                            bundle.putString("datetime", itemList.get(1).getDatetime());
                            bundle.putString("place_name", itemList.get(1).getPlace_name());
                            bundle.putString("image", itemList.get(1).getProducer_image());
                            bundle.putString("producer_name", itemList.get(1).getProducer_name());
                            bundle.putStringArray("pictures", itemList.get(1).getPicture());
                            bundle.putString("flag", itemList.get(1).getIconFlag());//获取头像flag
                            Intent intent = new Intent();
                            intent.putExtras(bundle);
                            intent.setClass(GuidesMainActivity.this, StraInfoActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            GuidesMainActivity.this.finish();
                        }
                    });
                    mh.tv_title1.setText(itemList.get(1).getTitle());
                    mh.tv_location1.setText(itemList.get(1).getPlace_name());
                    mh.tv_date1.setText(itemList.get(1).getDatetime());
                }
            }else{
                mh.iv_headImage.setVisibility(View.INVISIBLE);
                mh.iv_picture.setVisibility(View.INVISIBLE);
                mh.tv_title.setVisibility(View.INVISIBLE);
                mh.tv_location.setVisibility(View.INVISIBLE);
                mh.tv_date.setVisibility(View.INVISIBLE);
                mh.iv_headImage1.setVisibility(View.INVISIBLE);
                mh.iv_picture1.setVisibility(View.INVISIBLE);
                mh.tv_title1.setVisibility(View.INVISIBLE);
                mh.tv_location1.setVisibility(View.INVISIBLE);
                mh.tv_date1.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

        //定义一个HelpHolder
        class MyHolder {
            ImageView iv_picture, iv_headImage,iv_picture1, iv_headImage1;
            TextView tv_title, tv_location, tv_date,tv_title1, tv_location1, tv_date1;
        }
    }
    //在不进行输入时，输入键盘不显示
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            View v = getCurrentFocus();
            //如果不是落在EditText区域，则需要关闭输入法
            if (HideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean HideKeyboard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {

            int[] location = { 0, 0 };
            view.getLocationInWindow(location);

            //获取现在拥有焦点的控件view的位置，即EditText
            int left = location[0], top = location[1], bottom = top + view.getHeight(), right = left + view.getWidth();
            //判断我们手指点击的区域是否落在EditText上面，如果不是，则返回true，否则返回false
            boolean isInEt = (event.getX() > left && event.getX() < right && event.getY() > top
                    && event.getY() < bottom);
            return !isInEt;
        }
        return false;
    }
//    //按两次返回键关闭程序
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                Object mHelperUtils;
//                Toast.makeText(this, "再按一次退出APP", Toast.LENGTH_SHORT).show();
//                mExitTime = System.currentTimeMillis();
//            } else {
//                finish();
//            }
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
public boolean onKeyUp(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (isExit == false) {
            isExit = true;
            if (tExit != null) {
                tExit.cancel(); // 将原任务从队列中移除
            }
            // 重新实例一个定时器
            tExit = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            };
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            // 延时两秒触发task任务
            tExit.schedule(task, 2000);
        } else {
            finish();
            System.exit(0);
        }
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

    //动态申请读取手机内存的权限：
    private void requestWritePermission(){
        if (ActivityCompat.checkSelfPermission(GuidesMainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(GuidesMainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }
}
